<template>
  <view class="container">
    <view v-if="isLoading" class="loading-container">
      <text>加载检测结果中...</text>
    </view>
    <view v-else-if="currentRecord" class="result-view">
      <view class="title">
        <image
          class="detect-image"
          src="https://artist-eyes.obs.cn-south-1.myhuaweicloud.com/ppd/images/detect.png"
          mode="aspectFill"
        ></image>
      </view>
      <view class="result-container">
        <image mode="aspectFill" class="result-image" :src="currentRecord.res_image"></image>
        <view class="result-info">
          <view class="result-item">
            <text class="result-title">检测时间：</text>
            <text class="result-time result-text">{{ formatDate(currentRecord.created_at) }}</text>
          </view>
          <view class="result-item">
            <text class="result-title">检测结果：</text>
            <text 
              class="result-result result-text" 
              :class="getConclusionClass(currentRecord.result)">
              {{ currentRecord.result }}
            </text>
          </view>
          <view class="result-item">
            <text class="result-title">红肿块长度：</text>
            <text class="result-result result-text">
              {{ currentRecord.length ? currentRecord.length.toFixed(3) : 'N/A' }} (mm)
            </text>
          </view>
          <view class="result-item">
            <text class="result-title">红肿块宽度：</text>
            <text class="result-result result-text">
              {{ currentRecord.width ? currentRecord.width.toFixed(3) : 'N/A' }} (mm)
            </text>
          </view>
          <view class="result-item">
            <text class="result-title">红肿块平均直径：</text>
            <text class="result-result result-text">
              {{ currentRecord.size ? currentRecord.size.toFixed(3) : 'N/A' }} (mm)
            </text>
          </view>
          <view class="result-item">
            <text class="result-title">检测描述：</text>
            <text class="result-result result-text">
              {{ currentRecord.description || '暂无描述' }}
            </text>
          </view>
        </view>
      </view>
    </view>
    <view v-else class="no-data-container">
      <text>未找到检测记录</text>
      <button class="back-button" @click="goToDetect">去检测</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRecordStore } from '@/store/record'
import { useUserStore } from '@/store'
import { onShow } from '@dcloudio/uni-app'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const recordStore = useRecordStore()
const currentRecord = computed(() => recordStore.currentRecord)

// 添加加载状态
const isLoading = ref(true)

onShow(() => {
  init()
})

const init = async () => {
  isLoading.value = true
  try {
    // 确保用户信息存在
    if (!userInfo.value) {
      await userStore.getUserInfo()
    }
    
    // 如果已经有当前记录，直接显示
    if (recordStore.currentRecord) {
      isLoading.value = false
      return
    }
    
    // 加载记录列表
    await recordStore.getRecords(userInfo.value.id)
    
    // 确保当前记录存在
    if (!recordStore.currentRecord && recordStore.records && recordStore.records.length > 0) {
      // 设置最新记录为当前记录（假设最新记录是第一条）
      recordStore.setCurrentRecord(recordStore.records[0])
    }
    
    console.log('当前记录:', currentRecord.value)
  } catch (error) {
    console.error('加载记录失败:', error)
    uni.showToast({
      title: '加载记录失败',
      icon: 'error'
    })
  } finally {
    isLoading.value = false
  }
}

// 结论的样式根据不同结果变化
const getConclusionClass = (result: string) => {
  switch (result) {
    case '阴性':
      return 'conclusion-negative'
    case '一般阳性':
      return 'conclusion-normal-positive'
    case '中度阳性':
      return 'conclusion-moderate-positive'
    case '强阳性':
      return 'conclusion-severe-positive'
    default:
      return ''
  }
}

const formatDate = (date: string | Date) => {
  if (!date) return '未知时间'
  
  const d = new Date(date)
  if (isNaN(d.getTime())) return '无效时间'
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const goToDetect = () => {
  uni.switchTab({
    url: '/pages/detect/detect'
  })
}
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  padding: 0 15px 15px 15px;
  background: linear-gradient(180deg, rgba(215, 229, 247, 1) 0%, rgba(217, 234, 251, 0) 100%);
  min-height: 100vh;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  font-size: 16px;
  color: #888;
}

.no-data-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  text-align: center;
  
  .back-button {
    margin-top: 20px;
    background-color: #0075fe;
    color: white;
    width: 200px;
    border-radius: 12px;
  }
}

.title {
  width: 80%;
  height: 130px;
  margin: 0 auto;
  .detect-image {
    height: 100%;
  }
}

.result-container {
  width: 100%;
  padding: 10px;
  background-color: #fff;
  border-radius: 12px;
  display: flex; /* 修正拼写错误: diplay -> display */
  flex-direction: column;
  .result-image {
    height: 400px;
  }
  .result-info {
    margin-top: 5px;
    display: flex;
    flex-direction: column;
    .result-item {
      display: flex;
      min-height: 30px; /* 改为min-height适应多行文本 */
      align-items: center; /* 垂直居中 */
      margin-bottom: 8px; /* 增加间距 */
      
      .result-title {
        width: 40%;
        text-align: end;
        padding-right: 10px; /* 增加右间距 */
      }
      
      .result-text {
        flex: 1; /* 占据剩余空间 */
      }
    }
  }
}

.conclusion-negative {
  color: #28a745; /* 绿色 */
  font-weight: bold;
}

.conclusion-normal-positive {
  color: #e6d86b; /* 黄色 */
  font-weight: bold;
}

.conclusion-moderate-positive {
  color: #fd7e14; /* 橙色 */
  font-weight: bold;
}

.conclusion-severe-positive {
  color: #dc3545; /* 红色 */
  font-weight: bold;
}
</style>